/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-04-23 09:06:42
 * @Last Modified by: yudianyun
 * @Last Modified time: 2020-07-01 11:13:14
 * @Description: 备课页面 - 列表 - TabBar导航
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_main_tabbar.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/book/book.dart';
import 'package:flutter_code_framework/model_data/bookmenu/bookmenu.dart';
import 'package:flutter_code_framework/model_data/lesson/lesson.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/widgets/x_dialog_page.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';

import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'common/search.dart';
import 'common/select_book_menu.dart';
import 'lesson/book_list_pop_page.dart';
import 'lesson_publish.dart';

// ignore: must_be_immutable
class LessonsPage extends BaseWidget {
  LessonsPage({Key key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _LessonsPageState();
  }
}

class _LessonsPageState extends BaseWidgetState<LessonsPage> {
  //State _stateBaseFunction;
  int curPage = 1;
  int pageNum = 10;
  int total = 0;
  String createTime = '';
  bool noMoreFlag = false;
  ScrollController _controller = ScrollController();
  List<Object> listData = [null];
  String bookId = ""; //G.user.data.bookId.toString();
  String bookName =
      "选择教材"; // (G.user.data.bookName == null || G.user.data.bookName == "")
  // ? "选择教材"
  // : G.user.data.bookName;

  String bookMenuIds = "";

  List<int> selectids = [];

  bool isFirst = true;

  @override
  Widget buildWidget(BuildContext context) {
    return Column(children: <Widget>[
      Container(
        height: 70,
        margin: EdgeInsets.only(left: 24),
        child: IntrinsicHeight(
          child: Row(children: <Widget>[
            Row(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[
              Container(
                height: 30,
                //color: Colors.red,
                //padding: EdgeInsets.only(bottom:0),
                child: Text(
                  '备课',
                  style: TextStyle(
                    color: Theme.of(context).primaryTextTheme.caption.color,
                    fontSize: 22.0,
                    height: 1.1,
                  ),
                  //overflow:TextOverflow.visible ,
                ),
                alignment: Alignment.bottomLeft,
              ),
              Container(
                height: 30,
                //color: Colors.red,
                margin: EdgeInsets.only(left: 5, bottom: 2),
                child: Text('|',
                    //textAlign:TextAlign.end,
                    style: TextStyle(
                        color: Theme.of(context)
                            .primaryTextTheme
                            .caption
                            .color
                            .withOpacity(0.5),
                        fontSize: 13.0,
                        height: 1.1)),
                alignment: Alignment.bottomLeft,
              ),
              Container(
                height: 30,
                //color: Colors.red,
                margin: EdgeInsets.only(left: 5, bottom: 2),
                child: Text('Lessons',
                    //textAlign:TextAlign.end,
                    style: TextStyle(
                      color: Theme.of(context).cursorColor,
                      fontSize: 12.0,
                      height: 1.1,
                    )),
                alignment: Alignment.bottomLeft,
              ),
            ]),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(right: 15),
                child: IconButton(
                  icon: Icon(
                    SFSymbols.search,
                    size: 24,
                    color: Theme.of(context).primaryTextTheme.caption.color
                    //Color.fromRGBO(118,118,118,1)
                    ,
                  ),
                  onPressed: () {
                    //跳转搜索页
                    RouteTransition(new Search(resourceType: '备课'))
                        .pushReplacementRoute(context);
                  },
                  //padding : const EdgeInsets.all(8.0),
                  alignment: Alignment.centerRight,
                ),
              ),
            ),
          ]),
        ),
      ),
      Container(
        height: 50.0,
        color: Color.fromRGBO(216, 216, 216, 0.5),
        child:
            Row(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 24.0),
              child: GestureDetector(
                child: Text(
                  //"魂牵梦萦魂牵梦萦魂牵梦萦魂牵梦萦魂牵梦萦",
                  "${"bookName".length > 16 ? bookName.substring(0, 15) + "..." : bookName}",
                  style: TextStyle(
                      color: Theme.of(context).primaryColor, fontSize: 14.0),
                ),
                onTap: () => _selectBook(),
              ),
            ),
          ),
          Align(
            alignment: Alignment.centerRight,
            child: GestureDetector(
              child: Text(
                "选择章节",
                style: TextStyle(
                    color: Theme.of(context).primaryColor, fontSize: 14),
              ),
              onTap: () => _selectMenu(),
            ),
          ),
          SizedBox(
            width: 5,
          ),
          Padding(
            padding: EdgeInsets.only(right: 24.0),
            child: Icon(
              SFSymbols.menu,
              size: 16,
              color: Theme.of(context).primaryColor,
            ),
          ),
        ]),
      ),
      Expanded(
        child: Container(
          height: double.maxFinite,
          child: getListView(context),
        ),
      ),
      SizedBox(height: kTabbarHeigt),
    ]);
  }

  // ignore: missing_return
  GetSelectedBook getBook(
      String bookId, String bookName, String periodId, String subjectId) {
    if (bookName != null && bookName != "") {
      this.bookId = bookId;
      this.bookName = bookName;

      var userid = "";
      if (G.user != null && G.user.data != null && G.user.data.userId != null) {
        userid = G.user.data.userId;
      }
      setShareBook(userid);
      bookMenuIds = "";
      selectids = [];

      listData = new List<Object>();
      curPage = 1;
      getData(curPage);
    }
  }

  void _selectBook() {
    Navigator.of(context).push(new MaterialPageRoute(
        builder: (ctx) => new BookListPopPage(
              reBookId: this.bookId.toString(),
              reBookName: this.bookName,
              rePeriodId: G.user.data.periodId.toString(),
              reSubjectId: G.user.data.subjectId.toString(),
              callback: getBook,
            )));
  }

  // ignore: missing_return
  GetSelectedBookMenu selectmenucallback(List<BookMenu> selectlist) {
    if (selectlist != null && selectlist.length > 0) {
      List<int> ids = new List<int>();
      for (var item in selectlist) {
        ids.add(item.id);
      }
      selectids = ids;
      bookMenuIds = ids.join(",");
    } else {
      bookMenuIds = "";
    }
    curPage = 1;
    initData(false);
  }

  void _selectMenu() {
    showBottomSheetDialog(new SelectBookMenu(
        bookId: bookId,
        bookName: bookName,
        selectids: selectids,
        callback: selectmenucallback));
  }

  // void setShareBook() async {
  //   SharedPreferences _references = await SharedPreferences.getInstance();
  //   _references.setString("key_prelesson_bookid", this.bookId);
  //   _references.setString("key_prelesson_bookname", this.bookName);
  //   print("setShareBook bookId:"+bookId);
  //   print("setShareBook bookName:"+bookName);
  // }

  void setShareBook(String userId) async {
    SharedPreferences _references = await SharedPreferences.getInstance();
    _references.setString("key_prelesson_bookid_" + userId, this.bookId);
    _references.setString("key_prelesson_bookname_" + userId, this.bookName);
    // print("setShareBook bookId:"+bookId);
    // print("setShareBook bookName:"+bookName);
  }

  void getShareBook() async {
    SharedPreferences _references = await SharedPreferences.getInstance();
    var userid = "";
    if (G.user != null && G.user.data != null && G.user.data.userId != null) {
      userid = G.user.data.userId;
    }
    bookId = _references.getString("key_prelesson_bookid_" + userid);
    bookName = _references.getString("key_prelesson_bookname_" + userid);
    if (bookName == null || bookName == "") {
      bookName = "选择教材";
    }
    //print("getShareBook bookId:"+bookId??"");
    //print("getShareBook bookName:"+bookName??"");

    if (bookId == null || bookId == "") {
      G.req.bookData
          .getBookList(
        schoolId: G.user.data.schoolId.toString(),
        periodId: G.user.data.periodId.toString(),
        subjectId: G.user.data.subjectId.toString(),
        gradeId: G.user.data.gradeId.toString(),
      )
          .then((value) {
        if (value != null &&
            value.data["bookList"] != null &&
            value.data["bookList"].length > 0) {
          var list =
              value.data["bookList"].map((e) => Book.fromJson(e)).toList();
          print("list:" + list.toString());
          if (list != null && list.length > 0) {
            Book book = list[0];
            setState(() {
              this.bookId = book.id.toString();
              this.bookName = book.name.toString();
            });
            setShareBook(userid);
          }
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getShareBook();

    initData(false);
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        initData(true);
      }
    });
  }

  @override
  void onCreate() {
    // log("onCreate");
    setAppTopNavBarVisible(false);
    setListViewItemDel(true);
  }

  @override
  void onPause() {
    // log('onPause');
  }

  @override
  void onResume() {
    // log("onResume");
  }

  ///子类获取Listview ，重写相关方法自定义数据和布局。
  @override
  Widget getListView(BuildContext context) {
    Widget mainWidget;
    if (listData == null || listData.length == 0) {
      // if (isFirst) {
      //   // mainWidget = Center(
      //   //   child: CircularProgressIndicator(),
      //   // );
      //   setState(() {
      //     isFirst = false;
      //   });
      // } else {
      //   mainWidget = RefreshIndicator(
      //     child: getEmptyWidget(),
      //     onRefresh: _pullToRefresh,
      //   );
      // }
      mainWidget = getEmptyWidget();
    } else {
      mainWidget = RefreshIndicator(
        child: ListView.builder(
          shrinkWrap: true,
          //physics: NeverScrollableScrollPhysics(),
          //physics: BouncingScrollPhysics(),
          scrollDirection: Axis.vertical,
          itemCount: listData.length + 1,
          itemBuilder: (context, index) {
            //return _getSlidableItem(index);
            if (index == listData.length) {
              return _buildProgressMoreIndicator();
            } else {
              return _getSlidableItem(index);
            }
          },
          controller: _controller,
          physics: AlwaysScrollableScrollPhysics(),
        ),
        onRefresh: _pullToRefresh,
        // notificationPredicate: defaultScrollNotificationPredicate(),
      );
    }
    // }
    return mainWidget;
  }

  Widget _buildProgressMoreIndicator() {
    if (noMoreFlag) {
      if (listData == null || listData.length == 0) {
        //return Center(child: Text("暂无数据~"));
        return getEmptyWidget();
      }
      if (curPage == 1) {
        return Container();
      }
      return Container(
          alignment: Alignment.center,
          padding: EdgeInsets.all(16.0),
          child: Text(
            "----我是有底线的----",
            style: TextStyle(color: Colors.grey),
          ));
    } else {
      return Container(
          padding: const EdgeInsets.all(16.0),
          alignment: Alignment.center,
          child: SizedBox(
              width: 24.0,
              height: 24.0,
              child: CircularProgressIndicator(strokeWidth: 2.0)));
    }
  }

  Future<Null> _pullToRefresh() async {
    curPage = 1;
    ////下拉回调方法,方法需要有async和await关键字，没有await，刷新图标立马消失，没有async，刷新图标不会消失
    await initData(false);
    return null;
  }

  //滑动面板项目视图
  Widget _getSlidableItem(int index) {
    return Slidable(
      key: Key(listData[index] == null ? "" : listData[index].toString()),
      controller: slidableController,
      dismissal: SlidableDismissal(
        child: SlidableDrawerDismissal(),
        onWillDismiss: (type) {
          // showToastDialog('Are sure to Delete Operation!');
          return false;
        },
        onDismissed: (actionType) {
          listViewItemFunction(index);
        },
      ),
      //滑出选项的面板 动画
      actionPane: SlidableDrawerActionPane(), //_getActionPane(item.index),
      actionExtentRatio: 0.25,
      //Item 布局
      child: _renderRow(index),
      secondaryActions: <Widget>[        
        IconSlideAction(
          // caption: 'Delete',
          color: Color.fromRGBO(236, 115, 100, 1),
          // icon: Icons.delete,
          iconWidget: Text(
            '删除',
            style: TextStyle(color: Colors.white, fontSize: 16),
          ),
          onTap: () {
            listViewItemDelFunction(index);
          },
        ),
      ],
    );
  }

  //初始化项目结构
  Widget _renderRow(int index) {
    Widget itemWidget;
    itemWidget = Row(
      children: <Widget>[
        Expanded(
          child: getItemWidet(index),
        ),
      ],
    );

    return InkWell(
      child: Padding(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
        child: itemWidget,
      ),
      onTap: () {
        listViewItemFunction(index);
        //需独立context
        Slidable.of(context)?.renderingMode == SlidableRenderingMode.none
            ? Slidable.of(context)?.open()
            : Slidable.of(context)?.close();
      },
    );
  }

  ///ListView Item 单击事件
  @override
  void listViewItemFunction(int index) {
    Info model = listData[index];
    String lessonType = "图文";
    if (model.hasTW) {
      lessonType = '图文';
    } else if (model.hasAudio) {
      lessonType = '音频';
    } else if (model.hasVideo) {
      lessonType = '视频';
    } else if (model.hasXZY) {
      lessonType = '小作业';
    }
    Navigator.of(context).push(new MaterialPageRoute(
        builder: (ctx) => new LessonPublish(
              id: model.preLessonId,
              lessonType: lessonType,
            )));
  }

  @override
  void listViewItemDelFunction(int index) {
    setState(() {
      Info model = listData[index];
      // RouteTransition(XDialogPage(
      //   '确定要删除备课吗',
      //   callBack: () {
      //     delItem(model.preLessonId);
      //     //listData.removeAt(index);
      //   },
      // )).pushTransRoute(context);
      G.showToastDialog(context, "确定要删除备课吗", title: "提示", callBack: () {
        delItem(model.preLessonId);
      });
    });
  }

  ///初始化数据
  @override
  Future<Null> initData(bool isLoadMore) async {
    // 模拟等待3秒钟[]
    await Future.delayed(Duration(seconds: 1), () {
      //初始数据
      if (!isLoadMore) {
        listData = new List<Object>();
        getData(curPage);
      } else {
        if (!noMoreFlag) {
          ++curPage;
          getData(curPage);
        }
      }
    });
  }

  delItem(String id) async {
    var data = await G.req.lessonData.delLesson(id);
    if (data.data['isOk'] == true) {
      showNormalToast("删除成功！");
      RouteTransition(BaseMainTabbarPage())
          .pushAndRemoveUntilTransRoute(context);
    }
  }

  getData(int currentPageNum) async {
    var data = await G.req.lessonData.getPreLessonList(
        G.user.data.userId,
        int.parse(bookId),
        bookMenuIds,
        "",
        createTime,
        currentPageNum.toString(),
        pageNum.toString());
    if (mounted) {
      setState(() {
        total = int.parse(data.data["total"]);

        createTime = data.data["createTime"].toString();
        listData
            .addAll(data.data["info"].map((e) => Info.fromJson(e)).toList());
        if (listData == null || listData.length >= total) {
          noMoreFlag = true;
          // if (curPage > 1) {
          //   noMoreFlag = true;
          // } else {
          //   noMoreFlag = false;
          // }
        } else {
          noMoreFlag = false;
        }
      });
    }
  }

  ///获得Item控件布局 子类重写实现自定义布局 【注意】外层已加左右边距
  @override
  Widget getItemWidet(int index) {
    Info model = listData[index];
    List<Widget> books = [];
    if (model == null) {
      return Container();
    }
    if (model.hasTW) {
      books.add(Icon(SFSymbols.bookmark_fill, size: 16.0, color: Colors.green));
    } else if (model.hasAudio) {
      books.add(Icon(SFSymbols.bookmark_fill, size: 16.0, color: Colors.blue));
    } else if (model.hasVideo) {
      books
          .add(Icon(SFSymbols.bookmark_fill, size: 16.0, color: Colors.orange));
    } else if (model.hasXZY) {
      books.add(Icon(SFSymbols.bookmark_fill, size: 16.0, color: Colors.red));
    }

    return Container(
      height: 100.0,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 20.0),
          Container(height:25,child:
          Row(
            children: <Widget>[
              Text(
                "${model.title.length > 15 ? model.title.substring(0, 14) + "..." : model.title}",
                style: TextStyle(
                    color: Theme.of(context).primaryTextTheme.caption.color,
                    fontSize: 18.0),
              ),
              Icon(
                  (model.mobilePublish != null &&
                          model.mobilePublish == "Mobile"
                      ? SFSymbols.device_phone_portrait
                      : SFSymbols.device_desktop),
                  size: 16,
                  color: Theme.of(context).primaryColor),
            ],
          ),),
          SizedBox(height: 21.0),
          Container(height:20,child:
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  "创建时间：" + "${model.releaseTime}",
                  style: TextStyle(
                      color: Theme.of(context).primaryTextTheme.caption.color,
                      fontSize: 14.0),
                ),
              ),
              Align(
                  alignment: Alignment.centerRight,
                  child: Row(
                    children: books,
                  ))
            ],
          ),),
          SizedBox(height: 13.99),
          Divider(
              height: 0.01,
              color: Theme.of(context).primaryTextTheme.caption.color),
        ],
      ),
    );
  }
}
